package com.flying.common.runtime;

import org.apache.commons.lang3.time.StopWatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class TimeMeasureAspect {
    private final static Logger logger = LoggerFactory.getLogger(TimeMeasureAspect.class);

    @Around("execution(* com.flying..*.run(..))")
    public Object recordTime(ProceedingJoinPoint joinPoint) throws Throwable {
        //用 commons-lang 提供的 StopWatch 计时，Spring 也提供了一个 StopWatch
        StopWatch clock = new StopWatch();
        Object result = null;
        try {
            clock.start(); //计时开始
            result = joinPoint.proceed();//这个是我们监控的bean的执行并返回结果
            clock.stop(); //计时结束
        } catch (Throwable e) {
            logger.error("Time measure" + joinPoint + "with exception : " + e.getMessage());
            throw e;
        }
        if (logger.isInfoEnabled()) {
            logger.info("Time elapse:" + clock.getTime() + " ms [" + joinPoint.getTarget().toString() + "]");
        }
        return result;
    }
}
